<?php
ArrowController::importModel("org.arrowplatform.model.ArrowDataSource");
ArrowController::importModel("media.MediaFolder");
ArrowController::importModel("media.MediaFolder");
ArrowController::importModel("media.MediaApi");
ArrowController::importModel("media.MediaElement");
ArrowController::importModel("media.MediaTransformationProfile");
ArrowController::importModel("media.MediaElementConnection");
ArrowController::importModel("auth.Auth");
class ArrowMediaConnector extends ArrowTagContainer{
	
	protected $dataSource;
	
	private $field = null;
	private $listTable = null;
	private $currDirId = null;
	
	private $files = array();
	
	private $folder = null;
	private $parentFolder = null;
	
	private $currFileFieldId = "file";
	
	public function configure(){
		
		$this->addProperties(array(
			"state" => "list",
			"name" => "noname",
			"model" => null,
			"key" => null,
			"presentation" => "list",
			"files" => false,
			"initJsCallback" => "ctrlMediaConnectorInitCallback",
			"transformation" => '',
			"parentSystemName" => false,
			"targetSystemName" => false,
			"targetName" => false,
			"subFolderName" => false,
			"showImages" => true,
			"allowConnections" => true,
			"direct" => 0,
			"nameSuggestion" => false,
			"prefix" => "",
			"fromDisk" => true
		));
		$this->addRequiredProperties(array( "model", "key"));
		$this->addStateProperties(array("state", "selected"));
		$this->setContentCodeKept(true);
		
	}
	
	public function init(){
		
		

		
		$key = $this->getProperty("key");
		$model = $this->getProperty("model");
		
		ArrowController::importModel($model);
		if( $key ){
				$this->currFileFieldId.= $this->getId();
			
				$targetSysName = $this->getProperty("targetSystemName");
				$look = $targetSysName?$targetSysName:$model;
				$criteria = new Criteria();
				$criteria->addCondition( MediaFolder::F_SYSTEM_NAME,$look  );
				$folder = MediaFolder::getByCriteria( $criteria, MediaFolder::TCLASS );
				if(!empty($folder)){
					$this->folder = $folder[0];
				}else{
					
			 
				//Target folder creation
					$container = MediaApi::getSystemFolder();
					$parentSystemName = $this->getProperty("parentSystemName");
					if( $parentSystemName ){
						$criteria = new Criteria();
						$criteria->addCondition( MediaFolder::F_SYSTEM_NAME, $parentSystemName );
						$logicalParent = MediaFolder::getByCriteria( $criteria, MediaFolder::TCLASS );
						if(empty($logicalParent)){
							$container = MediaApi::createFolder( $container->getPKey(), $parentSystemName, $parentSystemName );
						}else{
							$container = $logicalParent[0];
						}
					}
					
					$name = $this->getProperty("targetName")?$this->getProperty("targetName"):"Container_{$look}";
					
					
					$criteria = new Criteria();
					$criteria->addCondition( MediaFolder::F_SYSTEM_NAME,$look  );
					$folder = MediaFolder::getByCriteria( $criteria, MediaFolder::TCLASS );
					if(empty($folder)){
						
						$this->folder = MediaApi::createFolder( $container->getPKey(), $name, $look );
					}else{
						$this->folder = $folder[0];
					}
				}
				
				$this->parentFolder = $this->folder;
					
				$subFolderName = $this->getProperty("subFolderName");
				if(!empty($subFolderName)){
					$criteria = new Criteria();
					$criteria->addCondition( MediaFolder::F_NAME, StringHelper::toValidFilesystemName( $subFolderName ) );
					$criteria->addCondition( MediaFolder::F_PARENT_ID, $this->folder->getPKey() );
					$subFolder = MediaFolder::getByCriteria( $criteria, MediaFolder::TCLASS );
					if(empty($subFolder)){
						$this->folder = MediaApi::createFolder( $this->folder->getPKey(), $subFolderName );
					}else{
						$this->folder = $subFolder[0];
					}
				}
				//-----------------------
				
			
			$critConnection = new Criteria("media.MediaElementConnection");
			$critConnection->addOrderBy("sort");
			$critConnection->addCondition( MediaElementConnection::F_MODEL, $model );
			$critConnection->addCondition( MediaElementConnection::F_OBJECT_ID, $key );
			$critConnection->addCondition( MediaElementConnection::F_NAME, $this->getProperty("name") );
			$critElement = new Criteria("media.MediaElement");
			
			$critTrack = new Criteria( "utils.track.Track" );
			$critTrack->setEmptyList();
			$critTrack->addColumn("date");
			/*$critTrack->startGroup( "OR" ) ;
			$critTrack->addCondition( "action", "create" );
			$critTrack->addCondition( "action", "NULL" );
			$critTrack->endGroup();
			$critTrack->startGroup( "OR" ) ;
			$critTrack->addCondition( "class", "MediaElementConnection" );
			$critTrack->addCondition( "class", "NULL" );
			$critTrack->endGroup();
			*/
			$critUser = new Criteria("auth.AuthUser");
			$critUser->setEmptyList();
			$critUser->addColumn( "login" );
			$critUser->addColumn( "name" );
			
			
			$criteria = new ArrowOrmJoinCriteria(array($critConnection,$critElement, $critTrack, $critUser ));
			// TODO: zamienić mediaElement na mediaElementConnector jak podepnie się tracka pod MediaElement Connector
			$criteria->addVirtualRelation( "MediaElementConnection", "id", "Track", "object_id" );
			$criteria->addJoinOnCondition( "Track", "MediaElementConnection",  'class = "MediaElementConnection" ' ) ;
			$criteria->addJoinOnCondition( "Track", "MediaElementConnection",  'action = "create" ' ) ;
			
			$result = MediaElementConnection::getDataSetByCriteria($criteria, MediaElementConnection::TCLASS);
			$this->files = $result;
			
			/*
			
			
			//$rowActions = $this->listTable->addNode("ui", "actionsGroup", array("name" => "row"));
			
			
			$link = ArrowTemplateLinker::getDefault()->generateBeanLink(array(
				"path" => "/controller::actionRouter",
				"action" => "delete",
				"model" => "media.MediaElement",
				"key" => '{$context[$key]}'
			));
			
			if( $this->getProperty("allowConnections") ){
				$rowActions->addNode("ui", "action", array("type" => "execute", "id" => "delete", "name" => "Usuń połączenie", "confirm" => 1))->setDisplay(false);
			}
			
			$a = $rowActions->addNode("ui", "action", array(
				"type" => "html", 
				"id" => "delete",
				"name" => "Usuń plik"
			));
			$a->setDisplay(false);
			$a->setContentCode('
				{assign var=key value="MediaElement:id"} 
				<a class="ctrl-media-connector-remove-connection" href="'.$link.'"> usuń plik</a>
			');
			
			
			$this->listTable->setCriteria( $criteria );
			$this->listTable->initAll();
			*/
	
		}
		
		
		$this->registerCssFile( "./server/standardModels/org/arrowplatform/controls/media/resources/ArrowMediaConnector.css" );
		$this->registerJs( get_class($this), dirname(__FILE__)."/resources/ArrowMediaConnector.js", "#ctrl-media-connector-".$this->getId(),array(
			"initJsCallback" => $this->getProperty("initJsCallback")
		));
		
	}
	
	public function generateBlockStart(){
		//exit("test");
		$str ='<div class="'.self::CTRL_NAMESPACE.'-media-connector -media-connector-multi" id="ctrl-media-connector-'.$this->getId().'" >';
		$key = $this->getProperty("key");
		if(empty($key)){
			$str.="Wymagany zapis obiektu aby go edytować</div>";
			return $str;
		}
		
		$str.= '<div class="ctrl-media-connector-top" >';
		$str.= '<div class="ctrl-media-connector-title">Połączone pliki</div>';
		if($this->getProperty("fromDisk"))
			$str.= '<div class="ctrl-media-connector-add-flash"><input type="file" id="'.$this->currFileFieldId.'" name="file" /></div>';
		
		
		if( $this->getProperty("allowConnections") )
	    	$str.= '<a href="" class="ctrl-media-connector-file-option ctrl-media-connector-add-local-show" title="Dodaj pliki wybierając z już załadowanych do dokumentów">Dodaj z dokumentów</a>';
		
		$str.= '<div style="clear: both;" ></div>';
		$str.= "</div>";
		
		$str.= '<div id="fileQueue'.$this->currFileFieldId.'" align="center"></div>';
		
		
		
		$str.=$this->generateAddBar();
		
		$downloadLink = $this->addNode("ui", "action", array(
			"type" => "execute", 
			"id" => "download", 
			"direct" => 1, 
			"model" => "media.MediaElement",
			"name" => "pobierz", 
			"confirm" => 1, 
			"class" => "ctrl-media-connector-file-option ctrl-media-connector-file-download"
		))->generate();
		
		$str.= '<div class="ctrl-media-connector-files" >';
		$even = false;
		foreach($this->files as $connection){
			$tmp = $connection->getRel("MediaElement");
			$el = reset( $tmp );
			
			$str.= '<div class="ctrl-media-connector-file ctrl-media-connector-file-'.($even?'even':'uneven').'" connectionId="'.$connection->getPKey().'">';
			if($el->isImage() && file_exists($el["path"])){
				$size = @getimagesize($el["path"]);
				$str.= '<div class="ctrl-media-connector-file-icon "><img size="'.$size[0]."x".$size[1].'" alt="'.$el["path"].'" src="'.$el->getSystemMiniature().'" class="ctrl-media-connector-file-icon-img" /></div>';
			}else{
				$tmp = explode( ".", $el["file"] );
				$str.= '<div class="ctrl-media-connector-file-icon ctrl-media-connector-file-icon-default ctrl-media-connector-file-icon-'. end($tmp) .' "></div>';
			}

			$str.= '<div class="ctrl-media-connector-options">';
			$str.= '<a href="'.$connection->getPKey().'" rel="'.$el->getPKey().'" class="ctrl-media-connector-file-option ctrl-media-connector-file-delete">usuń</a>';
			$str.= '<a href="'.$el->getPKey().'" class="ctrl-media-connector-file-option ctrl-media-connector-file-change-description">zmień opis</a>';
			$str.= '<a href="'.$el->getPKey().'" class="ctrl-media-connector-file-option ctrl-media-connector-file-rename">zmień nazwę</a>';
			$str.= str_replace( "#key#", $el->getPKey(), $downloadLink);
			$str.= '<a href="" class="ctrl-media-connector-file-option ctrl-media-connector-file-move">&nbsp;</a>';
			$str.= '</div>';
			$str.= '<div class="ctrl-media-connector-data">';
			$przez = "" ;
			if( !empty($connection["AuthUser:name"]) ) $przez = $connection["AuthUser:name"] ;
			else $przez = $connection["AuthUser:login"] ;
			$przez = $connection["Track:date"].' przez '.$przez ; 
			$str.= '<div class="ctrl-media-connector-file-title"><span>'.wordwrap($el["name"], 40, "<br />", true).'</span><div class="">['.$przez.']</div></div>';
			$str.= '<div style="clear: both;" ></div>';
			$str.= '<div class="ctrl-media-connector-file-description"><span>'.$el["description"].'</span></div>';
			$str.= '</div>';

			$str.= '<div style="clear: both;" ></div>';
			$str.= "</div>";
			$even = !$even;
		}
		$str.= "</div>";
		if($this->getProperty("fromDisk"))
			$str.= $this->generateAddButton();
		
		return $str."<div class=\"ctrl-media-elements-count\">".count($this->files)."</div></div>";
		 
	}
	public function generateBlockEnd(){
		return ""; 
	}
	
	
	private function generateAddBar(){
		$str = '<div class="ctrl-media-connector-add-bar">';
		
		$bind = $this->addNode("ui", "bind", array(
			"searchFields" => "id;name",
			"mode" => "multiAdvanced",
			"namespace" => 0,
			"value" => "",
			'ctrlId' => "bind-media-conn" . $this->getProperty("name")
		), false);
		$dataSource = $bind->addNode("data", "criteria", array());
		$dataSource->addNode("data", "model", array("model" => "media.MediaElement"));
		$dataSource->addNode("data", "model", array("model" => "media.MediaFolder"));
		
		$template = $bind->addNode("common", "template", array());
		
		$template->setContentCode('
			{assign var=folder value=$context->getRel(MediaFolder)}
			{if $context->isImage()}
				<img src="{$context->getSystemMiniature()}" style="float: left; margin-right: 5px;" />
			{/if}
			<b>{$context.name}</b>
			<div style="font-size: 10px;">{$folder.0->getPath(name,\' / \',1)} / {$folder.0.name}</div>
			<div style="clear: both;" ></div>
		');
		
		$dataSource->init();
		$bind->init();
		$str.=  '<div class="ctrl-media-connector-add-bind" >'.$bind->generate()."</div>";
		
		$model = $this->getProperty("model");
		$key = $this->getProperty("key");
		$name = $this->getProperty("name");
		
		$str.= '<a href="'.$model.'" rel="'.$key.'" alt="'.$name.'" class="ctrl-media-connector-file-option ctrl-media-connector-add-chosen" title="Dodaj wyszukane i wybrane elementy." style="float: left;">dodaj wybrane</a>';
		$str.=  $this->generateAddFromLocalAction();
		$str.= '<div style="clear: both;" ></div>';
		$str.= "</div>";
		return $str;
	}
	
	public function generateAddFromLocalAction(){
		$action = $this->addNode("ui", "action", array( 
	          'type' => 'dialog', 'name' => 'Przeglądaj',
	          'width' => 900, 'height' => 600,  
	          'template' => "/mediafolder::popupBrowser" ,'id' => 'create',
	          'class' => "ctrl-media-connector-file-option ctrl-media-connector-add",
	         ));
	     $action->addNode('ui', 'param', array('name' => 'model', 'value' => $this->getProperty("model") ));
	     $action->addNode('ui', 'param', array('name' => 'key', 'value' => $this->getProperty("key") ));
	     $action->addNode('ui', 'param', array('name' => 'ctrlId', 'value' => $this->getParent()->getId() ));
	     $action->addNode('ui', 'param', array('name' => 'name', 'value' => $this->getProperty("name") ));
	     $action->addNode('ui', 'param', array('name' => 'root', 'value' => $this->parentFolder->getPKey() ));
	     
	     if( $this->getProperty("transformation") ){
         	$criteria = new Criteria();
         	$criteria->addCondition(MediaTransformationProfile::F_SYSTEM_NAME, $this->getProperty("transformation"));
         	$profile = MediaTransformationProfile::getByCriteria( $criteria, MediaTransformationProfile::TCLASS );
         	$action->addNode('ui', 'param', array('name' => 'transformationId', 'value' => $profile[0]->getPKey() ));
        }
        
        $action->init();
        return $action->generate();
		
	}
	
	
	
	public function generateAddButton(){
		
		$model = $this->getProperty("model");
		$key = $this->getProperty("key");
		$name = $this->getProperty("name");
		
		$folderId = $this->folder->getPKey();
		$transformation = "0";
		if( $this->getProperty("transformation") ){
			$criteria = new Criteria();
			$criteria->addCondition(MediaTransformationProfile::F_SYSTEM_NAME, $this->getProperty("transformation"));
			$profile = MediaTransformationProfile::getByCriteria( $criteria, MediaTransformationProfile::TCLASS );
			
			if( !empty($profile) ){
				$profile = $profile[0];
				$transformation = $profile->getPKey(); 
			}else{
				throw new ArrowException(array("msg" => "Transformation not found", "transformation" => $this->getProperty("transformation")));
			}
		}
		
		$pFiles = $this->getProperty("files");
		if(empty($pFiles)){
			$files = "*.*;";
			$filesDesc = "Pliki";
		}else{
			$tmp = explode( ";", $this->getProperty("files"));
			$files = "";
			foreach($tmp as $ex)
				$files.="*.".$ex.";";
			$filesDesc = "Pliki: ". $files;
		}
		
		$res = ArrowResources::getDefault(ArrowController::$activeProject);
		$uploadify = $res->getResource("/js/jquery/uploadify/jquery.uploadify.v2.1.0.min.js")->getRelativePath();
		$uploadifyCss = $res->getResource("/js/jquery/uploadify/uploadify.css")->getRelativePath();
		$swfObject = $res->getResource("/js/swfobject/swfobject.js")->getRelativePath();
		$swf = $res->getResource("/js/jquery/uploadify/uploadify.swf")->getRelativePath();
		$deleteIcon = $res->getResource("/graphic/administration/icons/delete.gif")->getRelativePath();
		
		
		$bean =  ArrowTemplateLinker::getDefault()->generateBeanLink( array( "path" => "/controller::save" ), true);
		
		$stateChangeLink = $this->getStateChangeLink(array("state" => "list"),true);
		
		$ajaxCont = $this->getParent("ArrowCtrlAjax")->getId();
		
		$direct = $this->getProperty("direct");
		
    	$sessionId = session_id();
		
$str = <<<HTML
<script type="text/javascript" src="{$uploadify}"></script>
<script type="text/javascript" src="{$swfObject}"></script>
<link rel="stylesheet" type="text/css" href="{$uploadifyCss}" />
<style type="text/css">
	.uploadifyQueueItem{
		width: auto !important;
	}
</style>
<script type="text/javascript">
$(function() {
	var folderId = "{$folderId}";
	$("#{$this->currFileFieldId}").uploadify({
		'uploader'       : '{$swf}',
		'script'         : '{$bean}',
		'scriptData'	 : { 
			object: "media.MediaElement",
			"data[name_suggestion]": '{$this->getProperty("nameSuggestion")}',  
			"data[folder_id]":folderId, 
			"data[transformation_id]": '{$transformation}',
			"connection[model]": '{$model}',
			"connection[key]": '{$key}',
			"connection[name]": '{$name}',
			"connection[direct]": '{$direct}',
			"sessionId": '{$sessionId}'
		},
		'cancelImg'      : '{$deleteIcon}',
		'folder'         : 'uploads',
		'queueID'        : 'fileQueue{$this->currFileFieldId}',
		'buttonText'     : 'Z dysku',
		'width'			 : '75',
		'height'	 	 : '20',
		'auto'           : false,
		'multi'          : true,
		'fileDesc'		 : '{$filesDesc}',
		'fileExt'		 : '{$files}',
		'fileDataName'   : 'file',
		'auto'			 : true,
		onComplete: function (evt, queueID, fileObj, response)
   		{
   			eval('var res = '+response + ' ;');
   			ArrowResponseReader.read({ response: res });
   		},
   		onAllComplete: function(evt, data){
   			CtrlAjax.changeState( '{$ajaxCont}', '{$stateChangeLink}'   );
   		}
	});
});
</script>

HTML;

		
		return $str;
	}
	

}
?>